package com.markus.code.Thread;

import com.sun.org.apache.xerces.internal.xs.XSTerm;

/**
 * Author:markusZhang
 * Date:Create in 2020/9/8 0:22
 * todo: 生产者消费者问题
 */
public class ConProDemo {
    private int state = 1;
    public void printA() throws InterruptedException {
        synchronized (this){
            while(state != 1){
                this.wait();
            }
            System.out.println("Print A");
            state = 2;
            this.notifyAll();
        }
    }
    public void printB() throws InterruptedException {
        synchronized (this){
            while (state != 2){
                this.wait();
            }
            System.out.println("Print B");
            state = 3;
            this.notifyAll();
        }
    }
    public void printC() throws InterruptedException {
        synchronized (this){
            while(state != 3){
                this.wait();
            }
            System.out.println("Print C");
            state = 1;
            this.notifyAll();
        }
    }
    public static void main(String[] args) {
        ConProDemo demo = new ConProDemo();
        Thread thread1 = new Thread(new PrintA(demo));
        Thread thread2 = new Thread(new PrintB(demo));
        Thread thread3 = new Thread(new PrintC(demo));
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
class PrintA implements Runnable{

    ConProDemo demo;
    public PrintA(ConProDemo demo){
        this.demo = demo;
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++){
            try {
                demo.printA();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class PrintB implements Runnable{
    ConProDemo demo;
    public PrintB(ConProDemo demo){
        this.demo = demo;
    }
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            try {
                demo.printB();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class PrintC implements Runnable{
    ConProDemo demo;
    public PrintC(ConProDemo demo){
        this.demo = demo;
    }
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            try {
                demo.printC();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
